package com.mantru.iotpot.dishes

import android.app.Application
import android.util.Log
import androidx.databinding.ObservableField
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Bean.DishesCreateBean
import com.mantru.iotpot.Util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject

class DishesCreateViewModel(application: Application) : AndroidViewModel(application) {
    // 数据集合
    data class SpecData(
        val steep_type_Lists: MutableList<String> = mutableListOf(),
        val steep_index_Lists: MutableList<String> = mutableListOf(),
        var fire_value_Lists: MutableList<String> = mutableListOf(),
        var time_value_Lists: MutableList<String> = mutableListOf(),
        var time_long_Lists: MutableList<String> = mutableListOf(),
        var gripper_speed_value_Lists: MutableList<String> = mutableListOf(),
        var gripper_rotation_value_Lists: MutableList<String> = mutableListOf(),
        var gripper_position_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle1_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle2_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle3_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle4_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle5_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle6_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle7_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle8_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle9_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle10_value_Lists: MutableList<String> = mutableListOf(),
        var nozzle11_value_Lists: MutableList<String> = mutableListOf(),
        var box_need_avoid_Lists: MutableList<String> = mutableListOf(),
        var box_release_type_Lists: MutableList<String> = mutableListOf(),
        //自己新增的列表
        //调味料数据列表
        var nozzle_name_List_Lists: MutableList<MutableList<String>> = mutableListOf(),
        //固体料盒数据列表
        var nozzle_value_List_Lists: MutableList<MutableList<String>> = mutableListOf(),
        //盒子食材名称列表
        var box_name_List_Lists: MutableList<MutableList<String>> = mutableListOf(),
        //盒子食材名称列表
        var box_value_List_Lists: MutableList<MutableList<String>> = mutableListOf()
    )

    var steep_type_List = ObservableField<MutableList<String>>()
    var steep_index_List = ObservableField<MutableList<String>>()
    var fire_value_List = ObservableField<MutableList<String>>()
    var time_value_List = ObservableField<MutableList<String>>()
    var time_long_List = ObservableField<MutableList<String>>()
    var gripper_speed_value_List = ObservableField<MutableList<String>>()
    var gripper_rotation_value_List = ObservableField<MutableList<String>>()
    var gripper_position_value_List = ObservableField<MutableList<String>>()
    var nozzle1_value_List = ObservableField<MutableList<String>>()
    var nozzle2_value_List = ObservableField<MutableList<String>>()
    var nozzle3_value_List = ObservableField<MutableList<String>>()
    var nozzle4_value_List = ObservableField<MutableList<String>>()
    var nozzle5_value_List = ObservableField<MutableList<String>>()
    var nozzle6_value_List = ObservableField<MutableList<String>>()
    var nozzle7_value_List = ObservableField<MutableList<String>>()
    var nozzle8_value_List = ObservableField<MutableList<String>>()
    var nozzle9_value_List = ObservableField<MutableList<String>>()
    var nozzle10_value_List = ObservableField<MutableList<String>>()
    var nozzle11_value_List = ObservableField<MutableList<String>>()
    var box_need_avoid_List = ObservableField<MutableList<String>>()
    var box_release_type_List = ObservableField<MutableList<String>>()
    //自己新增的列表
    //调味料数据列表
    var nozzle_name_List_List = ObservableField<MutableList<MutableList<String>>>()
    //固体料盒数据列表
    var nozzle_value_List_List = ObservableField<MutableList<MutableList<String>>>()
    //盒子食材名称列表
    var box_name_List_List = ObservableField<MutableList<MutableList<String>>>()
    //盒子食材名称列表
    var box_value_List_List = ObservableField<MutableList<MutableList<String>>>()

    // 暴露给Activity的数据
    private val _dishesCreateList = MutableLiveData<MutableList<DishesCreateBean>>()
    val dishesCreateList: LiveData<MutableList<DishesCreateBean>> = _dishesCreateList
    // 是否显示空数据提示,并给予初始值true，表示可见
    private val _emptyTipVisible = MutableLiveData<Boolean>(true)
    val emptyTipVisible: LiveData<Boolean> = _emptyTipVisible
    //监听跳转事件
    private val _navigateSave = MutableLiveData<String>()
    val navigateSave: LiveData<String> = _navigateSave
    private val _navigateToCooking = MutableLiveData<Int>()
    val navigateToCooking: LiveData<Int> = _navigateToCooking
    //监听菜谱返回
    private val _faceImageValue = MutableLiveData<String>()
    val faceImageValue: LiveData<String> = _faceImageValue
    private val _numberValue = MutableLiveData<String>()
    val numberValue: LiveData<String> = _numberValue
    private val _weightValue = MutableLiveData<String>()
    val weightValue: LiveData<String> = _weightValue

    var numberList = ObservableField<MutableList<String>>()
    var weightList = ObservableField<MutableList<String>>()
    var name = ObservableField<String>("")
    var vegetableId = ObservableField<Int>(0)
    var vegetableImageUrl = ""
    // 用于存储不同 index 对应的数据
    val dataMap = mutableMapOf<Int, SpecData>()
    val applicationClass: ApplicationClass = application as ApplicationClass

    // 初始化viewModel
    init {
        initSpecData()
    }

    private fun initSpecData(){
        steep_type_List.set(mutableListOf())
        steep_index_List.set(mutableListOf())
        fire_value_List.set(mutableListOf())
        time_value_List.set(mutableListOf())
        time_long_List.set(mutableListOf())
        gripper_speed_value_List.set(mutableListOf())
        gripper_rotation_value_List.set(mutableListOf())
        gripper_position_value_List.set(mutableListOf())
        nozzle1_value_List.set(mutableListOf())
        nozzle2_value_List.set(mutableListOf())
        nozzle3_value_List.set(mutableListOf())
        nozzle4_value_List.set(mutableListOf())
        nozzle5_value_List.set(mutableListOf())
        nozzle6_value_List.set(mutableListOf())
        nozzle7_value_List.set(mutableListOf())
        nozzle8_value_List.set(mutableListOf())
        nozzle9_value_List.set(mutableListOf())
        nozzle10_value_List.set(mutableListOf())
        nozzle11_value_List.set(mutableListOf())
        box_need_avoid_List.set(mutableListOf())
        box_release_type_List.set(mutableListOf())
        nozzle_name_List_List.set(mutableListOf())
        nozzle_value_List_List.set(mutableListOf())
        box_name_List_List.set(mutableListOf())
        box_value_List_List.set(mutableListOf())
    }

    // 添加新项（允许插入操作，index为空则默认添加到最后）
    fun addItem(type: String, index: String) {
        // 获取当前列表长度
        val length = _dishesCreateList.value?.size?:0
        // 解析index参数
        //如果为空字符串则添加到最后，否则就插入到第index的位置
        val insertPos = when {
            index.isEmpty() -> length // 追加到末尾
            index.toIntOrNull()?.let { it in 0..length } == true -> index.toInt() // 有效插入位置
            else -> length // 无效数字或超出范围时追加
        }
        // 判断是插入还是追加操作
        val isInsert = insertPos < length

        // 统一操作函数（减少重复代码）
        fun <T> MutableList<T>?.safeAdd(pos: Int, value: T) {
            this?.let { list ->
                if (isInsert && pos <= list.size) {
                    list.add(pos, value)
                } else {
                    list.add(value)
                }
            }
        }

        // 添加空值的列表操作
        listOf(
            steep_type_List,
            steep_index_List,
            fire_value_List,
            time_value_List,
            time_long_List,
            gripper_speed_value_List,
            gripper_rotation_value_List,
            gripper_position_value_List,
            nozzle1_value_List,
            nozzle2_value_List,
            nozzle3_value_List,
            nozzle4_value_List,
            nozzle5_value_List,
            nozzle6_value_List,
            nozzle7_value_List,
            nozzle8_value_List,
            nozzle9_value_List,
            nozzle10_value_List,
            nozzle11_value_List,
            box_need_avoid_List,
            box_release_type_List,
        ).forEach { list ->
            // 根据类型设置值
            val value = when (list) {
                steep_type_List -> {
                    when (type) {
                        "加热设置" -> "1"
                        "调味料" -> "2"
                        "固体料盒" -> "3"
                        else -> "0" // 默认值
                    }
                }
                steep_index_List -> "" // 临时值，后面会重新索引
                fire_value_List -> "0"
                gripper_speed_value_List -> "0"
                gripper_rotation_value_List -> "0"
                gripper_position_value_List -> "1"
                box_need_avoid_List -> "0"
                nozzle1_value_List -> "0"
                nozzle2_value_List -> "0"
                nozzle3_value_List -> "0"
                nozzle4_value_List -> "0"
                nozzle5_value_List -> "0"
                nozzle6_value_List -> "0"
                nozzle7_value_List -> "0"
                nozzle8_value_List -> "0"
                nozzle9_value_List -> "0"
                nozzle10_value_List -> "0"
                nozzle11_value_List -> "0"
                else -> ""
            }
            list.get().safeAdd(insertPos, value)
        }
        //单独新增
        nozzle_name_List_List.get().safeAdd(insertPos, mutableListOf())
        nozzle_value_List_List.get().safeAdd(insertPos, mutableListOf())
        box_name_List_List.get().safeAdd(insertPos, mutableListOf())
        box_value_List_List.get().safeAdd(insertPos, mutableListOf())

        //重新给steep_index_List赋值，保证增删后所有的值都是按顺序排序
        reindexSteepList()

        updateDishesList()
    }

    // 删除项
    fun deleteItem(position: Int) {
        // 定义所有需要操作的列表
        listOf(
            steep_type_List,
            steep_index_List,
            fire_value_List,
            time_value_List,
            time_long_List,
            gripper_speed_value_List,
            gripper_rotation_value_List,
            gripper_position_value_List,
            nozzle1_value_List,
            nozzle2_value_List,
            nozzle3_value_List,
            nozzle4_value_List,
            nozzle5_value_List,
            nozzle6_value_List,
            nozzle7_value_List,
            nozzle8_value_List,
            nozzle9_value_List,
            nozzle10_value_List,
            nozzle11_value_List,
            box_need_avoid_List,
            box_release_type_List,
            nozzle_name_List_List,
            nozzle_value_List_List,
            box_name_List_List,
            box_value_List_List
        ).forEach { list ->
            list.get()?.removeAt(position)
        }

        //重新给steep_index_List赋值，保证增删后所有的值都是按顺序排序
        reindexSteepList()
        updateDishesList()
    }

    //重新给steep_index_List赋值，保证增删后所有的值都是按顺序排序
    private fun reindexSteepList() {
        steep_index_List.get()?.apply {
            forEachIndexed { index, _ ->
                this[index] = (index + 1).toString()
            }
        }
    }

    //判断当前是否可以添加步骤
    fun judgeAddItem(type: String): Boolean{
        //先判断上一个步骤是否填写完成
        if ( steep_type_List.get()!!.size > 0 ){
            //判断持续事件是否为空
            if ( time_value_List.get()!!.size > 0 ){
                for ( i in 0 until time_value_List.get()!!.size){
                    if ( time_value_List.get()!![i].isEmpty() ){
                        //Toast.makeText(getApplication(), "请先完善前面步骤的持续时间", Toast.LENGTH_SHORT).show()
                        ToastUtils.show(getApplication(), "请先完善前面步骤的持续时间")
                        return false
                    }
                }
            }
            if ( steep_type_List.get()!!.size > 0 ){
                for ( i in 0 until steep_type_List.get()!!.size){
                    when (steep_type_List.get()!![i]){
                        "1" ->{//加热设置

                        }
                        "2" ->{//调味料
                            //判断最调味料名称是否为空
                            if ( nozzle_name_List_List.get()!!.size > 0 ){
                                val listItem = nozzle_name_List_List.get()!![i]
                                if ( listItem.size > 0 ){
                                    for ( j in 0 until listItem.size ){
                                        if ( listItem[j].isEmpty() ){
                                            ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的调味料数据")
                                            return false
                                        }
                                    }
                                } else {
                                    ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的调味料数据")
                                    return false
                                }
                            }
                            //判断调味料重量是否为空
                            if ( nozzle_value_List_List.get()!!.size > 0 ){
                                val listItem = nozzle_value_List_List.get()!![i]
                                if ( listItem.size > 0 ){
                                    for ( j in 0 until listItem.size ){
                                        if ( listItem[j].isEmpty() ){
                                            ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的调味料数据")
                                            return false
                                        }
                                    }
                                } else {
                                    ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的调味料数据")
                                    return false
                                }
                            }
                        }
                        "3" ->{//固体料盒
                            //判断投菜方式是否为空
                            if ( box_release_type_List.get()!!.size > 0 ){
                                if ( box_release_type_List.get()!![i].isEmpty() ){
                                    //Toast.makeText(getApplication(), "请先完善当前步骤投菜方式", Toast.LENGTH_SHORT).show()
                                    ToastUtils.show(getApplication(), "请先完善当前步骤投菜方式")
                                    return false
                                }
                            }
                            //判断食材名称是否为空
                            if ( box_name_List_List.get()!!.size > 0 ){
                                val listItem = box_name_List_List.get()!![i]
                                if ( listItem.size > 0 ){
                                    for ( j in 0 until listItem.size ){
                                        if ( listItem[j].isEmpty() ){
                                            ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的食材数据")
                                            return false
                                        }
                                    }
                                } else {
                                    ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的食材数据")
                                    return false
                                }
                            }
                            //判断食材重量是否为空
                            if ( box_value_List_List.get()!!.size > 0 ){
                                val listItem = box_value_List_List.get()!![i]
                                if ( listItem.size > 0 ){
                                    for ( j in 0 until listItem.size ){
                                        if ( listItem[j].isEmpty() ){
                                            ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的食材数据")
                                            return false
                                        }
                                    }
                                } else {
                                    ToastUtils.show(getApplication(), "请先完善步骤"+ (i + 1) +"的食材数据")
                                    return false
                                }
                            }
                            //判断投菜避让是否为空
                            if ( box_need_avoid_List.get()!!.size > 0 ){
                                if ( box_need_avoid_List.get()!![i].isEmpty() ){
                                    //Toast.makeText(getApplication(), "请先选择当前步骤是否投菜避让", Toast.LENGTH_SHORT).show()
                                    ToastUtils.show(getApplication(), "请先选择当前步骤是否投菜避让")
                                    return false
                                }
                            }
                        }
                    }
                }
            }
            //判断type,如果是固体料盒，则判断非空的box_value_List_List的数量是否小于4，如果等于或大于4，则返回
            //如果是保存或者选择规格，则判断非空的box_value_List_List的数量是否小于等于4，如果大于4，则返回
            if ( box_value_List_List.get()!!.size > 0 ){
                if ( type == "保存" || type == "选择规格" || type == "时序图" ){
                    var num = 0
                    for ( i in 0 until box_value_List_List.get()!!.size ){
                        if ( box_value_List_List.get()!![i].isNotEmpty() ){
                            num++
                        }
                    }
                    if ( num > 4 ){//这里允许为4个
                        //Toast.makeText(getApplication(), "最多只有4个料盒，无法保存", Toast.LENGTH_SHORT).show()
                        ToastUtils.show(getApplication(), "最多只有4个料盒，无法保存")
                        return false
                    }
                } else if ( type == "固体料盒" ){
                    var num = 0
                    for ( i in 0 until box_value_List_List.get()!!.size ){
                        if ( box_value_List_List.get()!![i].isNotEmpty() ){
                            num++
                        }
                    }
                    if ( num >= 4 ){//这里等于4就不能添加了
                        //Toast.makeText(getApplication(), "最多只有4个料盒，无法新增", Toast.LENGTH_SHORT).show()
                        ToastUtils.show(getApplication(), "最多只有4个料盒，无法新增")
                        return false
                    }
                }
            }
        }
        return true
    }

    //判断当前是否所有规格都至少一个步骤
    fun judgeSaveAble(): Boolean{
        if ( steep_type_List.get()!!.size > 0 ){
            if ( dataMap.size < numberList.get()!!.size ) {
                //Toast.makeText(getApplication(), "请确保所有规格都至少有一个步骤", Toast.LENGTH_SHORT).show()
                ToastUtils.show(getApplication(), "请确保所有规格都至少有一个步骤")
                return false
            }
        }
        return true
    }

    // 更新菜谱研发列表数据
    fun updateDishesList() {
        //确保在主线程进行
        viewModelScope.launch(Dispatchers.Main) {
            val newList = mutableListOf<DishesCreateBean>()
            if (steep_index_List.get()?.isNotEmpty() == true){
                for ( i in 0 until steep_index_List.get()!!.size){
                    newList.add(
                        DishesCreateBean(
                            steep_type = steep_type_List.get()?.get(i).toString(),
                            steep_index = steep_index_List.get()?.get(i).toString(),
                            fire_value = fire_value_List.get()?.get(i).toString(),
                            time_value = time_value_List.get()?.get(i).toString(),
                            time_long = time_long_List.get()?.get(i).toString(),
                            gripper_speed_value = gripper_speed_value_List.get()?.get(i).toString(),
                            gripper_rotation_value = gripper_rotation_value_List.get()?.get(i).toString(),
                            gripper_position_value = gripper_position_value_List.get()?.get(i).toString(),
                            nozzle1_value = nozzle1_value_List.get()?.get(i).toString(),
                            nozzle2_value = nozzle2_value_List.get()?.get(i).toString(),
                            nozzle3_value = nozzle3_value_List.get()?.get(i).toString(),
                            nozzle4_value = nozzle4_value_List.get()?.get(i).toString(),
                            nozzle5_value = nozzle5_value_List.get()?.get(i).toString(),
                            nozzle6_value = nozzle6_value_List.get()?.get(i).toString(),
                            nozzle7_value = nozzle7_value_List.get()?.get(i).toString(),
                            nozzle8_value = nozzle8_value_List.get()?.get(i).toString(),
                            nozzle9_value = nozzle9_value_List.get()?.get(i).toString(),
                            nozzle10_value = nozzle10_value_List.get()?.get(i).toString(),
                            nozzle11_value = nozzle11_value_List.get()?.get(i).toString(),
                            box_need_avoid = box_need_avoid_List.get()?.get(i).toString(),
                            box_release_type = box_release_type_List.get()?.get(i).toString(),
                            sauceNameList = nozzle_name_List_List.get()?.get(i)?: mutableListOf(),
                            sauceValueList = nozzle_value_List_List.get()?.get(i)?: mutableListOf(),
                            foodNameList = box_name_List_List.get()?.get(i)?: mutableListOf(),
                            foodValueList = box_value_List_List.get()?.get(i)?: mutableListOf(),
                        )
                    )
                }
            }
            _dishesCreateList.postValue(newList)
            // 更新空数据提示的可见性
            _emptyTipVisible.value = newList.size <= 0
        }
    }

    fun saveCurrentSpecData(index: Int) {
        dataMap[index] = SpecData(
            steep_type_List.get()!!.toList().toMutableList(),
            steep_index_List.get()!!.toList().toMutableList(),
            fire_value_List.get()!!.toList().toMutableList(),
            time_value_List.get()!!.toList().toMutableList(),
            time_long_List.get()!!.toList().toMutableList(),
            gripper_speed_value_List.get()!!.toList().toMutableList(),
            gripper_rotation_value_List.get()!!.toList().toMutableList(),
            gripper_position_value_List.get()!!.toList().toMutableList(),
            nozzle1_value_List.get()!!.toList().toMutableList(),
            nozzle2_value_List.get()!!.toList().toMutableList(),
            nozzle3_value_List.get()!!.toList().toMutableList(),
            nozzle4_value_List.get()!!.toList().toMutableList(),
            nozzle5_value_List.get()!!.toList().toMutableList(),
            nozzle6_value_List.get()!!.toList().toMutableList(),
            nozzle7_value_List.get()!!.toList().toMutableList(),
            nozzle8_value_List.get()!!.toList().toMutableList(),
            nozzle9_value_List.get()!!.toList().toMutableList(),
            nozzle10_value_List.get()!!.toList().toMutableList(),
            nozzle11_value_List.get()!!.toList().toMutableList(),
            box_need_avoid_List.get()!!.toList().toMutableList(),
            box_release_type_List.get()!!.toList().toMutableList(),
            nozzle_name_List_List.get()!!.map { it.toMutableList() }.toList().toMutableList(),
            nozzle_value_List_List.get()!!.map { it.toMutableList() }.toList().toMutableList(),
            box_name_List_List.get()!!.map { it.toMutableList() }.toList().toMutableList(),
            box_value_List_List.get()!!.map { it.toMutableList() }.toList().toMutableList()
        )
    }

    fun loadDateForIndex(index: Int) {
        if (dataMap.containsKey(index)) {
            val specData = dataMap[index]!!
            steep_type_List.set(specData.steep_type_Lists.toList().toMutableList())
            steep_index_List.set(specData.steep_index_Lists.toList().toMutableList())
            fire_value_List.set(specData.fire_value_Lists.toList().toMutableList())
            time_value_List.set(specData.time_value_Lists.toList().toMutableList())
            time_long_List.set(specData.time_long_Lists.toList().toMutableList())
            gripper_speed_value_List.set(specData.gripper_speed_value_Lists.toList().toMutableList())
            gripper_rotation_value_List.set(specData.gripper_rotation_value_Lists.toList().toMutableList())
            gripper_position_value_List.set(specData.gripper_position_value_Lists.toList().toMutableList())
            nozzle1_value_List.set(specData.nozzle1_value_Lists.toList().toMutableList())
            nozzle2_value_List.set(specData.nozzle2_value_Lists.toList().toMutableList())
            nozzle3_value_List.set(specData.nozzle3_value_Lists.toList().toMutableList())
            nozzle4_value_List.set(specData.nozzle4_value_Lists.toList().toMutableList())
            nozzle5_value_List.set(specData.nozzle5_value_Lists.toList().toMutableList())
            nozzle6_value_List.set(specData.nozzle6_value_Lists.toList().toMutableList())
            nozzle7_value_List.set(specData.nozzle7_value_Lists.toList().toMutableList())
            nozzle8_value_List.set(specData.nozzle8_value_Lists.toList().toMutableList())
            nozzle9_value_List.set(specData.nozzle9_value_Lists.toList().toMutableList())
            nozzle10_value_List.set(specData.nozzle10_value_Lists.toList().toMutableList())
            nozzle11_value_List.set(specData.nozzle11_value_Lists.toList().toMutableList())
            box_need_avoid_List.set(specData.box_need_avoid_Lists.toList().toMutableList())
            box_release_type_List.set(specData.box_release_type_Lists.toList().toMutableList())
            nozzle_name_List_List.set(specData.nozzle_name_List_Lists.toList().toMutableList())
            nozzle_value_List_List.set(specData.nozzle_value_List_Lists.toList().toMutableList())
            box_name_List_List.set(specData.box_name_List_Lists.toList().toMutableList())
            box_value_List_List.set(specData.box_value_List_Lists.toList().toMutableList())

            updateDishesList()
        } else {
            initSpecData()
            updateDishesList()
        }
    }

    fun saveSpecsData(type: String){
        val json = JSONObject()
        json.put("vegetable_name", name.get().toString())
        //这里要把url转为文件形式进行保存,如果原本是http开头的网路图片，则换成文件形式，否则直接保存
        val savePath = if ( vegetableImageUrl.startsWith("http") ){
            "file:///data/user/0/com.mantru.iotpot/files/" + vegetableImageUrl.replace("http://iotapi.mantru.com/upload/share_image/","")
        } else {
            vegetableImageUrl
        }
        json.put("face_image_url", savePath)
        val spec_data = JSONArray()
        if ( !numberList.get().isNullOrEmpty() ){
            for ( i in 0 until numberList.get()!!.size ){
                val spec_dataItem = JSONObject()
                spec_dataItem.put("copies_qty", numberList.get()!![i].replace("份", ""))
                spec_dataItem.put("weight", weightList.get()!![i])
                val steep_data = JSONArray()
                if (dataMap.isNotEmpty()){
                    val specData = dataMap[i]
                    if (specData != null) {
                        if ( specData.steep_type_Lists.isNotEmpty() ){
                            for ( k in 0 until specData.steep_type_Lists.size ){
                                val steep_dataItem = JSONObject()
                                steep_dataItem.put("steep_type", specData.steep_type_Lists[k])
                                steep_dataItem.put( "steep_index", specData.steep_index_Lists[k])
                                steep_dataItem.put( "fire_value", specData.fire_value_Lists[k])
                                steep_dataItem.put( "time_value", specData.time_value_Lists[k])
                                steep_dataItem.put( "time_long", specData.time_long_Lists[k])
                                steep_dataItem.put( "gripper_speed_value", specData.gripper_speed_value_Lists[k])
                                steep_dataItem.put( "gripper_rotation_value", specData.gripper_rotation_value_Lists[k])
                                steep_dataItem.put( "gripper_position_value", specData.gripper_position_value_Lists[k])
                                steep_dataItem.put( "nozzle1_value", specData.nozzle1_value_Lists[k])
                                steep_dataItem.put( "nozzle2_value", specData.nozzle2_value_Lists[k])
                                steep_dataItem.put( "nozzle3_value", specData.nozzle3_value_Lists[k])
                                steep_dataItem.put( "nozzle4_value", specData.nozzle4_value_Lists[k])
                                steep_dataItem.put( "nozzle5_value", specData.nozzle5_value_Lists[k])
                                steep_dataItem.put( "nozzle6_value", specData.nozzle6_value_Lists[k])
                                steep_dataItem.put( "nozzle7_value", specData.nozzle7_value_Lists[k])
                                steep_dataItem.put( "nozzle8_value", specData.nozzle8_value_Lists[k])
                                steep_dataItem.put( "nozzle9_value", specData.nozzle9_value_Lists[k])
                                steep_dataItem.put( "nozzle10_value", specData.nozzle10_value_Lists[k])
                                steep_dataItem.put( "nozzle11_value", specData.nozzle11_value_Lists[k])
                                steep_dataItem.put( "box_need_avoid", specData.box_need_avoid_Lists[k])
                                steep_dataItem.put( "box_release_type", specData.box_release_type_Lists[k])
                                val box_data = JSONArray()
                                val nameList = specData.box_name_List_Lists[k]
                                val valueList = specData.box_value_List_Lists[k]
                                for (m in nameList.indices) {
                                    val boxItem = JSONObject()
                                    boxItem.put("name", nameList[m])
                                    boxItem.put("value", valueList[m])
                                    box_data.put(boxItem)
                                }
                                steep_dataItem.put( "box_data", box_data)
                                steep_data.put(steep_dataItem)
                            }
                        }
                    }
                }
                spec_dataItem.put("steep_data", steep_data)
                spec_data.put(spec_dataItem)
            }
        }
        json.put("spec_data", spec_data)
        val map: MutableMap<String, Any> = HashMap()
        map["vegetable_id"] = vegetableId.get().toString().toInt()
        map["json_data"] = json
        //如果锅正在复位，则不给保存
        if ( type == "保存并炒制" && applicationClass.pot_position_value > 3 ){
            ToastUtils.show(applicationClass, "锅复位中，暂时无法保存")
            return
        }
        getHttpValue("SaveSQLData_Vegetable_Entity", map, type)
    }

    // 清空所有数据
    private fun clearAllData() {
        dataMap.clear()
        initSpecData() // 重置所有 ObservableField 列表
    }

    private fun parseBaseInfo(data: JSONObject) {
        name.set(data.getString("vegetable_name"))
        //在这里把图片传到activity处理，存疑
        _faceImageValue.postValue(data.getString("face_image_url"))
    }

    private fun parseSpecData(specArray: JSONArray) {
        for (i in 0 until specArray.length()) {
            val specItem = specArray.getJSONObject(i)
            // 解析 copies_qty 和 weight
            parseNumberAndWeight(specItem)
            //为每个规格创建独立的 SpecData
            val specData = SpecData()
            val specDataList = specItem.getJSONArray("steep_data")
            Log.d("GetSQLData_Vegetable_Entity_For_Edit", "specDataList: $specDataList")
            if ( specDataList.length() > 0 ){
                //先对specDataList以步骤来排序
                val listLength = specDataList.length()
                val mutableList = mutableListOf<JSONObject>()
                for (j in 0 until listLength) {
                    mutableList.add(specDataList.getJSONObject(j))
                }
                // 对steep_index进行排序，越小越靠前
                mutableList.sortWith { obj1, obj2 ->
                    val index1 = obj1.getString("steep_index").toIntOrNull() ?: Int.MAX_VALUE
                    val index2 = obj2.getString("steep_index").toIntOrNull() ?: Int.MAX_VALUE
                    index1.compareTo(index2)
                }
                // 直接对 specData 的各个列表赋值
                for (j in 0 until mutableList.size) {
                    val item = mutableList[j]
                    specData.steep_type_Lists.add(item.getString("steep_type"))
                    specData.steep_index_Lists.add(item.getString("steep_index"))
                    specData.fire_value_Lists.add(item.getString("fire_value"))
                    specData.time_value_Lists.add(item.getString("time_value"))
                    specData.time_long_Lists.add(item.getString("time_long"))
                    specData.gripper_speed_value_Lists.add(item.getString("gripper_speed_value"))
                    specData.gripper_rotation_value_Lists.add(item.getString("gripper_rotation_value"))
                    specData.gripper_position_value_Lists.add(item.getString("gripper_position_value"))
                    specData.nozzle1_value_Lists.add(item.getString("nozzle1_value"))
                    specData.nozzle2_value_Lists.add(item.getString("nozzle2_value"))
                    specData.nozzle3_value_Lists.add(item.getString("nozzle3_value"))
                    specData.nozzle4_value_Lists.add(item.getString("nozzle4_value"))
                    specData.nozzle5_value_Lists.add(item.getString("nozzle5_value"))
                    specData.nozzle6_value_Lists.add(item.getString("nozzle6_value"))
                    specData.nozzle7_value_Lists.add(item.getString("nozzle7_value"))
                    specData.nozzle8_value_Lists.add(item.getString("nozzle8_value"))
                    specData.nozzle9_value_Lists.add(item.getString("nozzle9_value"))
                    specData.nozzle10_value_Lists.add(item.getString("nozzle10_value"))
                    specData.nozzle11_value_Lists.add(item.getString("nozzle11_value"))
                    specData.box_need_avoid_Lists.add(item.getString("box_need_avoid"))
                    specData.box_release_type_Lists.add(item.getString("box_release_type"))
                    if (specData.nozzle_name_List_Lists.size <= j) {
                        specData.nozzle_name_List_Lists.add(mutableListOf())
                    }
                    if (specData.nozzle_value_List_Lists.size <= j) {
                        specData.nozzle_value_List_Lists.add(mutableListOf())
                    }
                    if (specData.box_name_List_Lists.size <= j) {
                        specData.box_name_List_Lists.add(mutableListOf())
                    }
                    if (specData.box_value_List_Lists.size <= j) {
                        specData.box_value_List_Lists.add(mutableListOf())
                    }
                    if ( item.getString("nozzle1_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("生抽")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle1_value"))
                    }
                    if ( item.getString("nozzle2_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("老抽")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle2_value"))
                    }
                    if ( item.getString("nozzle3_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("蚝油")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle3_value"))
                    }
                    if ( item.getString("nozzle4_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("动物油")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle4_value"))
                    }
                    if ( item.getString("nozzle5_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("植物油")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle5_value"))
                    }
                    if ( item.getString("nozzle6_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("盐水")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle6_value"))
                    }
                    if ( item.getString("nozzle7_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("醋")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle7_value"))
                    }
                    if ( item.getString("nozzle8_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("淀粉水")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle8_value"))
                    }
                    if ( item.getString("nozzle9_value") != "0" ){
                        specData.nozzle_name_List_Lists[j].add("烹饪水")
                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle9_value"))
                    }
//                    if ( item.getString("nozzle10_value") != "0" ){
//                        specData.nozzle_name_List_Lists[j].add("烹饪水")
//                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle10_value"))
//                    }
//                    if ( item.getString("nozzle11_value") != "0" ){
//                        specData.nozzle_name_List_Lists[j].add("洗锅水")
//                        specData.nozzle_value_List_Lists[j].add(item.getString("nozzle11_value"))
//                    }

                    if (item.has("box_data")) {
                        val boxDataArray = item.getJSONArray("box_data")
                        if ( boxDataArray.length() > 0 ){
                            for (m in 0 until boxDataArray.length()) {
                                val boxItem = boxDataArray.getJSONObject(m)
                                specData.box_name_List_Lists[j].add(boxItem.getString("name"))
                                specData.box_value_List_Lists[j].add(boxItem.getString("value"))
                            }
                        }
                    }
                }
            }
            //将规格数据存入 dataMap
            dataMap[i] = specData
        }
        loadDateForIndex(0)
    }

    private fun parseNumberAndWeight(specItem: JSONObject) {
        val currentNumberList = numberList.get() ?: mutableListOf()
        val currentWeightList = weightList.get() ?: mutableListOf()

        currentNumberList.add(specItem.getString("copies_qty") + "份")
        currentWeightList.add(specItem.getString("weight"))

        numberList.set(currentNumberList)
        weightList.set(currentWeightList)
        //在这里设置初始currentSelectedIndex，并设置初始规格和份量
        if ( !numberList.get().isNullOrEmpty() && !weightList.get().isNullOrEmpty() ){
            _numberValue.postValue(numberList.get()!![0])
            _weightValue.postValue(weightList.get()!![0])
        }
    }

    //获取网络数据
    fun getHttpValue(api: String, map: Map<String, Any>, type: String){
        when ( api ){
            "SaveSQLData_Vegetable_Entity" ->{//保存菜谱
                val jsonData = applicationClass.SaveSQLData_Vegetable_Entity(map["vegetable_id"] as Int, map["json_data"] as JSONObject)
                if (!jsonData.isNullOrEmpty()) {
                    try {
                        val jsonObject = JSONObject(jsonData)
                        val success = jsonObject.getBoolean("success")
                        if (success) {
                            when (type){
                                "保存" ->{
                                    //Toast.makeText(applicationClass, "保存成功", Toast.LENGTH_SHORT).show()
                                    ToastUtils.show(applicationClass, "保存成功")
                                    _navigateSave.postValue("")
                                }
                                "保存并炒制" ->{
                                    ToastUtils.show(applicationClass, "保存成功")
                                    val vegetableId = jsonObject.getInt("vegetable_id")
                                    _navigateToCooking.postValue(vegetableId)
                                }
                            }
                        } else {
                            Log.e("---SaveSQLData_Vegetable_Entity", "API返回success=false")
                        }
                    } catch (e: Exception){
                        Log.e("---SaveSQLData_Vegetable_Entity:",e.toString())
                    }
                } else {
                    Log.e("---SaveSQLData_Vegetable_Entity", "返回的JSON数据为空")
                }
            }
            "GetSQLData_Vegetable_Entity_For_Edit" -> {//读取菜谱数据
                val jsonData = applicationClass.GetSQLData_Vegetable_Entity_For_Edit(map["vegetable_id"] as Int)
                if (!jsonData.isNullOrEmpty()) {
                    try {
                        val jsonObject = JSONObject(jsonData)
                        val success = jsonObject.getBoolean("success")
                        val data = jsonObject.getJSONObject("data")
                        if (success) {
                            // 清空旧数据
                            clearAllData()
                            // 解析基础信息
                            parseBaseInfo(data)
                            // 解析规格数据
                            parseSpecData(data.getJSONArray("spec_data"))
                        } else {
                            Log.e("---GetSQLData_Vegetable_Entity", "API返回success=false")
                        }
                    } catch (e: Exception){
                        Log.e("---GetSQLData_Vegetable_Entity:",e.toString())
                    }
                } else {
                    Log.e("---SaveSQLData_Vegetable_Entity", "返回的JSON数据为空")
                }
            }
        }
    }
}